<script lang="ts" setup>
import {reactive} from "vue";
import {ElMessage} from "element-plus";
import service from "@/utils/request";
import {useCounterStore} from "@/stores/counter";
import {useRouter} from "vue-router";

const store = useCounterStore();
const router = useRouter();

const vehicleLogin = reactive({
  username: "sunqi",
  password: "123",
  isAgree: 0,
});

const registerForm = reactive({
  name: "",
  vehicleLicense: "",
  seatCapacity: "",
  username: "",
  email: "",
  phone: "",
  password: "",
  confirmPassword: "",
  rAgree: 0,
});

// 对象转字符串后，其中的id取到并存储
function getAdcVehicleId(vehicleString) {
  const startIdx = vehicleString.indexOf("id=") + 3;
  const endIdx = vehicleString.indexOf(",", startIdx);
  return vehicleString.substring(startIdx, endIdx);
}

const login = () => {
  service.post("/vehicle/login", vehicleLogin).then((res) => {
    if (res.success) {
      localStorage.setItem("token", res.data.token);
      localStorage.setItem('user', res.data.user);
      const userId = getAdcVehicleId(res.data.user);  // 提取ID函数
      localStorage.setItem('userId', userId);
      router.push({path: "/search"});
      connectWebSocket();
    } else {
      ElMessage.error("用户名或密码错误！");
    }
  });
};

function connectWebSocket() {
  let userId = localStorage.getItem('userId');
  const wsUrl = `${import.meta.env.VITE_BASE_WS}/websocket-vehicletrip/${userId}`;

  if ("WebSocket" in window) {
    let ws = new WebSocket(wsUrl);
    store.setWebsocket(ws);
  } else {
    alert("不支持websocket");
  }

  store.websocket.onerror = function () {
    console.log("WebSocket连接发生错误");
  };

  store.websocket.onopen = function () {
    console.log("WebSocket连接成功");
  };

  store.websocket.onmessage = function (event) {
    console.log(event.data);
    store.setMessage(event.data);  // 设置消息内容到store
    store.isDialogTrue(); // 打开对话框
  };
}

// 注册方法
const register = () => {
  service.post('/vehicle/addVehicle', registerForm)
      .then(
          response => {
            console.log('成功', response.success)
            if (response.success == true) {
              alert("注册成功")
              location.reload();
            } else {
              alert("注册失败")
            }

          }
      )
}

const confirmFunc = () => {
  if (registerForm.confirmPassword !== registerForm.password)
    ElMessage.error("密码与确认密码不一致.");
};
</script>

<template>
  <div class='header'>
  </div>
  <div class="layout">

    <el-tabs type="border-card">
      <el-tab-pane label="登录">
        <el-form class="loginForm" label-position="right" label-width="60px" style="max-width: 460px">
          <el-form-item label="用户名">
            <el-input v-model="vehicleLogin.username"/>
          </el-form-item>
          <el-form-item label="密码">
            <el-input v-model="vehicleLogin.password" type="password"/>
          </el-form-item>
          <el-row>
            <el-checkbox v-model="vehicleLogin.isAgree" class="checkBox" label="同意用户使用准则" name="type"/>
          </el-row>
          <el-button v-if="vehicleLogin.isAgree" class="loginBtn" type="primary" @click="login">
            登录
          </el-button>
        </el-form>
      </el-tab-pane>

      <el-tab-pane label="注册">
        <el-form
            class="loginForm"
            label-position="right"
            label-width="100px"
            style="max-width: 460px"
        >

          <el-form-item label="姓名：">
            <el-input v-model="registerForm.name"/>
          </el-form-item>
          <el-form-item label="车牌号：">
            <el-input v-model="registerForm.vehicleLicense"/>
          </el-form-item>
          <el-form-item label="乘车人数：">
            <el-input v-model="registerForm.seatCapacity"/>
          </el-form-item>
          <el-form-item label="用户名：">
            <el-input v-model="registerForm.username"/>
          </el-form-item>
          <el-form-item label="邮箱：">
            <el-input v-model="registerForm.email"/>
          </el-form-item>
          <el-form-item label="电话：">
            <el-input v-model="registerForm.phone"/>
          </el-form-item>
          <el-form-item label="密码：">
            <el-input v-model="registerForm.password" type="password"/>
          </el-form-item>
          <el-form-item label="确认密码：">
            <el-input
                v-model="registerForm.confirmPassword"
                type="password"
                @blur="confirmFunc"
            />
          </el-form-item>

          <el-row>
            <el-checkbox
                v-model="registerForm.rAgree"
                class="checkBox"
                label="同意用户使用准则"
                name="type"
            />
          </el-row>
          <el-button
              v-if="registerForm.rAgree"
              class="loginBtn"
              type="primary"
              @click="register"
          >
            注册
          </el-button>
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<style scoped>
.header {
  display: flex;
  justify-content: space-between;
  background-color: #BDDCFF;
  background-image: url("../assets/login.png");
  background-size: 100% 100%;
  height: 120px;
  line-height: 60px;
  color: #495e77;
  padding: 0 12px;

}

.layout {

  position: absolute;

  top: 20%;
  width: 100%;
}

.loginBtn {
  width: 100px;
}

.loginForm {
  text-align: center;
}

.checkBox {
  margin-left: 7px;
}

.inpWidth {
  width: 165px;
}
</style>
